package com.meiqiongproperty.yiguanjia.utils.image;


import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;

import com.ctrip.android.asyncimageloader.cache.memory.MemoryCacheAware;
import com.ctrip.android.asyncimageloader.core.ImageLoader;
import com.ctrip.android.asyncimageloader.core.assist.FailReason;
import com.ctrip.android.asyncimageloader.core.assist.ImageLoadingListener;
import com.meiqiongproperty.yiguanjia.R;
import com.meiqiongproperty.yiguanjia.utils.Utils;

import java.io.File;

/**
 * @author Chen
 * @version V1.0
 * @package com.sameway.cnotes.utils.image
 * @date 17/2/6
 */
public class CImageLoadingListener implements ImageLoadingListener {
    private ImageView.ScaleType mScaleType = ImageView.ScaleType.CENTER_CROP;

    @Override
    public void onLoadingCancelled(String imageUri, View view) {
    }

    @Override
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        if (view == null)
            return;

        ImageView imageView = (ImageView) view;
        if (Utils.emptyOrNull(imageUri) || loadedImage == null) {
            cleanMemByUrl(imageUri);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setImageResource(R.mipmap.ic_launcher);
        } else {
            imageView.setScaleType(mScaleType);
        }
    }

    @Override
    public void onLoadingFailed(String imageUri, View view,
                                FailReason failReason) {
        if (view == null)
            return;

        cleanMemByUrl(imageUri);
        ImageView imageView = (ImageView) view;
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setImageResource(R.mipmap.ic_launcher);
    }

    @Override
    public void onLoadingProgress(int imageUri) {
    }

    @Override
    public void onLoadingStarted(String imageUri, View view) {
        if (view == null)
            return;

        ImageView imageView = (ImageView) view;
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setImageResource(R.mipmap.ic_launcher);
    }

    public void setLoadingCompleteScaleType(ImageView.ScaleType _scaleType) {
        mScaleType = _scaleType;
    }


    private void cleanMemByUrl(String imageUri) {
        MemoryCacheAware<String, Bitmap> mem = ImageLoader.getInstance().getMemoryCache();
        if (mem.get(imageUri) != null) {
            mem.remove(imageUri);
        }

        File file = ImageLoader.getInstance().getDiscCache().get(imageUri);
        if (file != null && file.exists()) {
            file.delete();
        }
    }
}